package com.echo.week;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author echo
 * @Description Condition条件案例--三小哥洗剪吹  A->B->C
 * @Date 2023/10/21.
 * @Version 1.0
 */
public class DemCondition {

    public static void main(String[] args) {
        ShareData shareData = new ShareData();

            new Thread(()->{
                for (int i = 0; i <10 ; i++) {
                    shareData.wash();
                }
            },"Toney-A正在为顾客").start();

        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                shareData.cut();
            }
        },"Toney-B正在为顾客").start();

        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                shareData.blow();
            }
        },"Toney-C正在为顾客").start();
    }

    static class ShareData {
        private volatile int number = 1;//任务角色1->A,2->B,3->C

        private  Lock lock = new ReentrantLock();

        private  Condition c1 = lock.newCondition(); //A  洗头
        private  Condition c2 = lock.newCondition();//B 理发
        private  Condition c3 = lock.newCondition();//C 吹头

        //洗头
        public void wash() {
            lock.lock();
            try {
                while (number != 1) {
                    c1.await();
                }
                //执行任务
                System.out.println(Thread.currentThread().getName()+"\t洗头");
                //唤醒B
                number = 2;
                c2.signal();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }finally {
                lock.unlock();
            }
        }


        // 理发
        public void cut(){
            lock.lock();
            try {
                while (number != 2) {
                    c2.await();
                }
                //执行任务
                System.out.println(Thread.currentThread().getName()+"\t理发");
                //唤醒C
                number = 3;
                c3.signal();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }finally {
                lock.unlock();
            }
        }

        //吹发
        public void blow(){
            lock.lock();
            try {
                while (number != 3) {
                    c3.await();
                }
                //执行任务
                System.out.println(Thread.currentThread().getName()+"\t吹头发");
                //唤醒A
                number = 1;
                c1.signal();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }finally {
                lock.unlock();
            }
        }

    }
}
